import axios from '@/util/axios';
import { Url } from '@/config';
import formatSongs from '@/util/song';

axios.defaults.baseURL = Url.baseUrl.dev;

// 排行榜列表
export function getToplistDetail() {
  return axios.get('/toplist/detail');
}
// 推荐歌单
export function getPersonalized() {
  return axios.get('/personalized');
}
// 获取歌曲详情
export function getMusicDetail(ids) {
  return axios.get('/song/detail', {
    params: {
      ids,
    },
  });
}
// 歌单详情
export function getPlaylistDetail(id) {
  return new Promise((resolve) => {
    axios.get('/playlist/detail', {
      params: {
        id,
      },
    }).then(({ playlist }) => playlist)
      .then((playlist) => {
        const playlists = playlist;
        // 判断歌单歌曲数据是否整
        if (playlist.trackIds.length === playlist.tracks.length) {
          playlists.tracks = formatSongs(playlist.tracks);
          resolve(playlist);
        }
        // 默认最大加载歌单歌曲数量
        const ids = playlist.trackIds
          .slice(0, 500)
          .map((v) => v.id)
          .toString();
        getMusicDetail(ids).then((item) => {
          playlists.tracks = formatSongs(item.songs);
          resolve(playlist);
        });
      });
  });
}

// 相关歌曲推荐
export function getSimiSong(id) {
  return new Promise((resolve) => {
    axios.get('/simi/song', {
      params: {
        id,
      },
    }).then((playlist) => {
      const playlists = playlist;
      const ids = playlists.songs
        .slice(0, 500)
        .map((v) => v.id)
        .toString();
      // 获取歌曲详情数据
      getMusicDetail(ids).then((item) => {
        // 格式化歌曲数据
        playlists.songs = formatSongs(item.songs);
        resolve(playlists.songs);
      });
    });
  });
}
// 获取音乐地址
export function getMusicUrl(id) {
  return axios.get('/song/url', {
    params: {
      id,
    },
  });
}
